define([
    'Util',
    'text!tpl/sprint/addSprint.tpl',
    'dialog',
    'select',
    'date',
    'form',
    'jquery',
    'validator',
    'cookie',
    '../common/getPath',
    '../common/dateDiff',
    'comboSelect',
    '../common/dateFormat'
],function (Util, SprintTpl,Dialog, Select, MyDate, Form, $, Validator, $cookie, AjaxPath, computeDaysDelta, ComboSelect) {

    require(['style!css/style.css']);
    var _indexModule=null,
        tabSprint=null,
        cycData=null,
        cycSelect=null,
        cycSelectValue=null,
        SprintStartTime=null,
        SprintEndTime=null,
        addSprValidation=null,
        addSprintCountVal=null,
        addSprintData=null;
    //定义jquery类型的元素$el
    var $el = $(SprintTpl);
    //定义初始化函数
    var initialize = function(indexModule, options, tabItem){
        _indexModule=indexModule;
        addSprintData=options;
        $(tabItem).on("tabActive", function() {
            tabItem.show(true); //刷新表单
        });
        tabSprint = tabItem;
        //将根节点赋值给接口
        this.content = $el;
        sprintStatus();
        cycle();
        initDate();
        addSprintValidation();
        eventInit();
    };
    //按钮事件
    var eventInit = function (){
        //页面除dialog按钮功能
        $el.on('click', '.btnBack', btnBack);//返回
        $el.on('click', '.btnSprintBack', btnBack);//返回迭代列表
        $el.on('click', '.addSprintSaveBtn', addSprintSaveBtn);//保存
        $el.on('click', '.sprintStatus a', sprintStatusTagA);//状态转换
    };
    /*返回*/
    var btnBack = function() {
        tabSprint.switchTab(addSprintData.menuId);
        tabSprint.destroy("addSprintTab");
        $('.addSprintTitle',$el).val("");
        $('.addSprintCount',$el).val("");
        $('#SprintStartTime input',$el).val(new Date().Format("yyyy-MM-dd"));
        $('.SprintEndTime',$el).val("");
        $('.describe',$el).val("");
        $('.sprintDo',$el).addClass('t-btn-blue').siblings().removeClass('t-btn-blue').addClass('t-btn-white');
        cycle();

    };
    var statusBtn=function () {
        var status=$('.sprintStatus a',$el);
        for(i=0; i<status.length;i++){
            if(status.eq(i).hasClass('t-btn-blue')){
                return status.eq(i).attr("key");
            }
        }
    };
    /*保存*/
    var addSprintSaveBtn=function () {
        //console.log(cycSelectValue.name);
        var objSprint={
            "systemId":$cookie.get("projectSelectId"),
            "sprintName":$('.addSprintTitle',$el).val(),
            "status":statusBtn(),
            "description":$('.describe',$el).val(),
            "cycleNum":$('.addSprintCount',$el).val(),
            "cycleDate":cycSelectValue.name,
            "startTime": $('#SprintStartTime input',$el).val(),
            "endTime":$('.SprintEndTime',$el).val(),
            "userId":$cookie.get("userId")
        };
        Util.ajax.postJson(AjaxPath.project+"/sprints/", JSON.stringify(objSprint), function(result, isok) {
            if(addSprValidation.form()) {
                //console.log(result);
                if (result.returnCode === "0000") {
                    new Dialog({
                        mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                        title: '提示',
                        width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                        height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                        cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                        ok: function() {
                            btnBack();
                        }, // 点击确定按钮的回调函数，可为空。如果指定 return false 则执行完方法后不关闭弹窗，默认 return true。若不配置该项，则不会出现确定按钮。
                        okValue: '确定', //确定按钮的文本 默认是 ‘ok’
                        modal: true,
                        content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                    });

                } else {
                    new Dialog({
                        mode: 'confirm', // 对话框模式，默认normal标准|confirm浮动层|confirm确认对话框
                        title: '提示',
                        width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                        height: 120, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                        cancelDisplay: false, //是否显示取消按钮（强制执行，可在confirm模式下生效），可选项。 默认true(显示)
                        modal: true,
                        content: '<div style="text-align:center;margin-top:50px">' + result.returnMessage + '</div>'// 对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
                    });
                }

            }else{
                console.log('验证失败');
            }

        },"application/json")

    };
    /*状态转换*/
    var sprintStatusTagA=function () {
        $(this).addClass('t-btn-blue');
        $(this).siblings().removeClass('t-btn-blue').addClass('t-btn-white');
    };
    /*状态接口*/
    var sprintStatus=function () {
        Util.ajax.getJson(AjaxPath.project+"/dropdown?modual=sprint&type=sprintStatus", {}, function(result, isok) {
            if(result.returnCode==="0000"){
                $('.sprintDo',$el).attr("key",0);
                $('.sprintDoing',$el).attr("key",1);
                $('.sprintDone',$el).attr("key",2);
            }
        })
    };
    /*年月日秒时分*/
    var DateAdd=function(interval, number, date){
        switch (interval) {
            case "y ": {
                date.setFullYear(date.getFullYear() + number);
                return date;
                break;
            }
            case "m ": {
                date.setMonth(date.getMonth() + number);
                return date;
                break;
            }
            case "w ": {
                date.setDate(date.getDate() + number * 7);
                return date;
                break;
            }
            case "d ": {
                date.setDate(date.getDate() + number);
                return date;
                break;
            }
            case "h ": {
                date.setHours(date.getHours() + number);
                return date;
                break;
            }
            case "m ": {
                date.setMinutes(date.getMinutes() + number);
                return date;
                break;
            }
            case "s ": {
                date.setSeconds(date.getSeconds() + number);
                return date;
                break;
            }
            default: {
                date.setDate(d.getDate() + number);
                return date;
                break;
            }
        }
    };
    /*迭代周期中天数/周/月数*/
    var addSprintCount=function (obj) {
        dataSprint=parseInt($('.addSprintCount',$el).val());
        addSprintCountVal=$('.addSprintCount',$el).val();
        var now = new Date();
         if(addSprintCountVal===""|| dataSprint<=0 ||  isNaN( addSprintCountVal )|| dataSprint.length>3){
             $('.SprintEndTime',$el).val("");
             return false;
         }else{
             // 加多少天/月/周.
             var newDate = DateAdd(obj, dataSprint, now);
             $('.SprintEndTime',$el).val(newDate.Format("yyyy-MM-dd"));
         }
    };
    /*迭代周期*/
    var cycle=function () {
        cycData=[
                {
                    "key":"天",
                    "name":"天"
                },
                {
                    "key":"周",
                    "name":"周"
                },
                {
                    "key":"个月",
                    "name":"个月"
                }
            ];
        var cycConfig = {
            el:$("#cyc", $el),       //要绑定的容器
            name:'name',    //下拉框单元添加name属性
            checked:'0',        //默认选中
            datas: cycData         //数据源与url模式可二选一
        };
        cycSelect= new ComboSelect(cycConfig);
        cycSelectValue= cycSelect.getSelected();
        if(cycSelectValue.name==="天"){
                addSprintCount("d ");
            $el.on('blur', '.addSprintCount', function () {
                addSprintCount("d ");
            });
        }
        cycSelect.change(function(e){

            cycSelectValue= cycSelect.getSelected();
            if(e.target.selectedIndex===0){
                    addSprintCount("d ");
                    cycleSelectChange();
                $el.on('blur', '.addSprintCount', function () {
                    addSprintCount("d ");
                    cycleSelectChange();
                });
            }else if(e.target.selectedIndex===1){
                    addSprintCount("w ");
                    cycleSelectChange();
                $el.on('blur', '.addSprintCount', function () {
                    addSprintCount("w ");
                    cycleSelectChange();
                });
            }else if(e.target.selectedIndex===2){
                    addSprintCount("m ");
                    cycleSelectChange();
                $el.on('blur', '.addSprintCount', function () {
                    addSprintCount("m ");
                    cycleSelectChange();
                });
            }
            //console.log('你选择了第' + e.target.selectedIndex + '项，值是' + e.target.value)
        })
    };
    /*当时间改变的时候*/
    var cycleSelectChange = function (type) {
        type=cycSelect.getSelected();
        console.log(type);
        var timeStr=$('#SprintStartTime input',$el).val();
        var startTimeVal = Date.parse(new Date(timeStr));
        var endTimeVal = null;
        if(type.name==='天'){
            endTimeVal = startTimeVal+86400000*$('.addSprintCount',$el).val();
        }else if(type.name==='周'){
            endTimeVal = startTimeVal+7*86400000*$('.addSprintCount',$el).val();
        }else{
            endTimeVal = new Date(startTimeVal);
            endTimeVal.setMonth( endTimeVal.getMonth()+Number($('.addSprintCount',$el).val()));
        }
        $('.SprintEndTime',$el).val(new Date(endTimeVal).Format("yyyy-MM-dd"))
    };

    /*开始时间 结束时间*/
    var initDate = function() {
        //开始时间
        SprintStartTime = new MyDate({
            el:$("#SprintStartTime", $el),
            inputClassName: 'date',
            label: '<i style="color:red;padding:2px;">*</i>开始时间:',
            name: ' SprintStartTime',    //开始日期文本框name
            isReadOnly: true,  //项可设置日期输入框是否只读
            range: false,
            type: "date",
            isDisabled: false,//是否禁用组件
            defaultValue: nowTime(0,'yyyy-MM-dd'),
            btns: ['clear', 'now', 'confirm'],
            done: function(dates,value,proposeDate){
                cycleSelectChange();
            }
        });
    };

/*表单验证*/
    var addSprintValidation = function() {
        addSprValidation = new Validator({
            el: $(".addSprintForm", $el),
            submitBtn: $(".addSprintSaveBtn",$el), //触发验证的按钮，可不配置
            dialog: true, //是否弹出验证结果对话框
            pattern: { intege1:"^[1-9]\\d*$" },
            rules: {
                addSprintTitle: "required",
                addSprintCount: "required|intege1",
                SprintStartTime: "required",
                SprintEndTime: "required"
            },
            messages: {
                addSprintTitle: {
                    required: "迭代名称不能为空！"
                },
                addSprintCount: {
                    required: "迭代周期不能为空",
                    intege1:"请输入正整数"
                },
                SprintStartTime: {
                    required: "开始时间不能为空"
                },
                SprintEndTime: {
                    required: "结束时间不能为空"
                }
            }
        });
    };
    //将初始化函数返回
    return initialize;
});